package jhu.bookstore;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class Controller
 */
public class Controller extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public Controller() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();
        HttpSession session = request.getSession();

        String url = "";
        List<Book> cart = (ArrayList<Book>) session.getAttribute("cart");
        User currentUser = (User) session.getAttribute("currentUser");


        if (userPath.equals("/home")) {
            url = "index.jsp";
        }

        if (userPath.equals("/addToCart")) {
            if (cart == null) {
                cart = new ArrayList<Book>();
                session.setAttribute("cart", cart);
            }

            String bookId = request.getParameter("productId");
            String name = request.getParameter("bookName");
            String price = request.getParameter("price");
            if (bookId != null || !bookId.isEmpty()) {
                Book b = new Book(Integer.parseInt(bookId), name, "", "", Double.parseDouble(price), "");
                cart.add(b);
            }
            url = "index.jsp";
        }

        if (userPath.equals("/removeItem")) {

            String index = request.getParameter("indexToRemove");
            double total = 0;
            if (cart != null) {
                cart.remove(Integer.parseInt(index));
                for (int i = 0; i < cart.size(); i++) {
                    total += cart.get(i).getPrice();
                }
            }
            session.setAttribute("cart", cart);
            session.setAttribute("subtotal", total);

            url = "cart.jsp";
        }

        if (userPath.equals("/viewCart")) {
            String clear = request.getParameter("clearCart");

            if (cart != null && clear != null && clear.equals("CLEAR")) {
                cart.clear();
            }
            session.setAttribute("cart", cart);

            double total = 0;
            if (cart != null) {
                for (int i = 0; i < cart.size(); i++) {
                    total += cart.get(i).getPrice();
                }
            }
            session.setAttribute("subtotal", total);
            url = "cart.jsp";
        }

        if (userPath.equals("/checkout")) {
            if (currentUser == null) {
                session.setAttribute("isUserNull", "true");
            } else {
                session.setAttribute("isUserNull", "false");
            }
            double total = 0;
            if (cart != null) {
                int size = cart.size();
                for (int i = 0; i < size; i++) {
                    total += cart.get(i).getPrice();
                }
                session.setAttribute("cartSize", size);
            }

            session.setAttribute("subtotal", total);
            url = "checkout.jsp";
        }

        if (userPath.equals("/confirm")) {
            if (currentUser != null) {
                if (DBHelperFactory.getDBHelper().authenticateUser(currentUser)) {
                    session.setAttribute("currentUser", (User) currentUser);
                }
            } else {
                currentUser = new User();
                session.setAttribute("currentUser", null);
            }

            double total = 0;
            if (cart != null) {
                DBHelper helper = DBHelperFactory.getDBHelper();
                Map<Book, Integer> purchaseMap = new HashMap<Book, Integer>();
                for (int i = 0; i < cart.size(); i++) {
                    if (purchaseMap.containsKey(cart.get(i))) {
                        Integer quantity = purchaseMap.get(cart.get(i));
                        purchaseMap.put(cart.get(i), quantity + 1);
                    } else {
                        purchaseMap.put(cart.get(i), 1);
                    }
                }
                if (currentUser.getId() != null) {
                    for (Map.Entry<Book, Integer> entry : purchaseMap.entrySet()) {
                        helper.makeSale(entry.getKey().getBookId(), currentUser.getId(), entry.getValue());
                    }
                }
            }

            //reset the cart
            //the user has completed their purchase
            session.setAttribute("cart", null);
            request.setAttribute("confirmation_cart", cart);
            url = "confirmation.jsp";
        }

        if (userPath.equals("/login")) {
            session.setAttribute("authentication", "NA");
            url = "login.jsp";
        }

        if (userPath.equals("/registration")) {
            session.setAttribute("registered", "NA");
            url = "registration.jsp";
        }

        if (userPath.equals("/registerUser")) {
            if (currentUser == null) {
                currentUser = new User();
                session.setAttribute("currentUser", currentUser);
            }

            DBHelper helper = DBHelperFactory.getDBHelper();
            int userID = 2 + helper.getUserCount();
            System.out.println("getting user count " + helper.getUserCount() );
            System.out.println("the user ID  " + userID);

            System.err.println(userID);
            currentUser.setId(userID);
            currentUser.setName(request.getParameter("username"));
            currentUser.setPassword(request.getParameter("password"));

            if (helper.addUser(currentUser)) {
                session.setAttribute("registered", "success");
                session.setAttribute("currentUser", (User) currentUser);
                url = "registration.jsp";
            } else {
                session.setAttribute("currentUser", null);
                session.setAttribute("registered", "failure");
                url = "registration.jsp";
            }

        }

        if (userPath.equals("/loginUser")) {
            if (currentUser == null) {
                currentUser = new User();
                session.setAttribute("currentUser", currentUser);
            }

            DBHelper helper = DBHelperFactory.getDBHelper();
            int userID = 2 + helper.getUserCount();

            System.err.println(userID);
            currentUser.setName(request.getParameter("username"));
            currentUser.setPassword(request.getParameter("password"));

            System.err.println(helper.authenticateUser(currentUser));
            if (helper.authenticateUser(currentUser)) {
                session.setAttribute("currentUser", (User) currentUser);
                session.setAttribute("authentication", "success");
                url = "login.jsp";
            } else {
                session.setAttribute("currentUser", null);
                session.setAttribute("authentication", "failure");
                url = "login.jsp";
            }
        }


        if (userPath.equals("/logout")) {

            session.setAttribute("authentication", null);
            session.setAttribute("currentUser", null);
            session.invalidate();
            url = "index.jsp";
        }

        // use RequestDispatcher to forward request internally

        request.getRequestDispatcher(url).forward(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);

    }
}
